package cn.pconline.autoclub.service;

import java.util.Collections;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.gelivable.dao.GeliDao;
import org.gelivable.dao.GeliOrm;
import org.gelivable.dao.Mid;
import org.gelivable.dao.SqlBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.EmptyResultDataAccessException;

import cn.pconline.autoclub.entity.ClubForum;
import cn.pconline.autoclub.entity.UserForum;

/**
 * @author zhouruxuan
 * @date 2015年5月8日 下午12:23:00
 */
public class UserForumService {

    @Autowired
    private GeliOrm geliOrm;
    @Autowired
    private GeliDao geliDao;
    @Autowired
    private IntfService intfService;
    private static final Logger log = LoggerFactory.getLogger(UserForumService.class);

    /**
     * 创建用户、车友圈关系
     *
     * @param userForum
     * @return
     */
    public long create(UserForum userForum) {
        return geliDao.create(userForum);
    }

    /**
     * 如果用户没有加入过车友圈，就通过省市和车系信息初始化
     *
     * @param userId
     * @param cityId
     * @param provinceId
     * @param carInfo 品牌ID;品牌名称;车系ID;车系名称
     * @return
     */
    public int createIfNothing(long userId, long cityId, long provinceId, String carInfo) {
        if (userId==0 || (StringUtils.isEmpty(carInfo) && cityId == 0 && provinceId == 0)) {
            return 0;
        }
        SqlBuilder sql = new SqlBuilder();
        sql.appendSql("select count(1) from ").appendSql(geliOrm.getTableName(UserForum.class, userId));
        sql.appendSql(" where user_id = ").appendValue(userId);
        long total = geliDao.count(sql.getSql(), sql.getValues());
        if (total > 0) {
            return 0;
        }
        String[] ss = carInfo.split(";");
        long serialId = 0;
        if (ss.length == 4) {
            try {
                serialId = Long.parseLong(ss[2]);
            } catch (java.lang.NumberFormatException e) {
                log.error("--dirty data----:{}", carInfo);
            }
        }
        return create(userId, cityId, provinceId, serialId);
    }
    
    /**
     * 如果用户没有加入过车友圈，就通过省市和车系信息初始化
     *
     * @param userId
     * @param cityId
     * @param provinceId
     * @param serialId
     * @return
     */
    public int createIfNothing(long userId, long cityId, long provinceId, long serialId) {
        if (userId==0 || (serialId==0 && cityId == 0 && provinceId == 0)) {
            return 0;
        }
        SqlBuilder sql = new SqlBuilder();
        sql.appendSql("select count(1) from ").appendSql(geliOrm.getTableName(UserForum.class, userId));
        sql.appendSql(" where user_id = ").appendValue(userId);
        long total = geliDao.count(sql.getSql(), sql.getValues());
        if (total > 0) {
            return 0;
        }
        return create(userId, cityId, provinceId, serialId);
    }

    /**
     * 通过省市和车系ID创建用户
     *
     * @return
     */
    public int create(long userId, long cityId, long provinceId, long serialId) {
        //除了广州和深圳要求城市版块，其他只要省份版块
        if (cityId == 440100 || cityId == 440300) {//广州或者深圳
            provinceId = 0;
        } else {
            cityId = 0;
        }
        List<ClubForum> list = intfService.listClubForums(0, serialId, provinceId, cityId);
        int count = 0;
        for (ClubForum f : list) {
            if (findByUserIdFourmId(userId, f.getForumId()) != null) {
                continue;
            }
            UserForum uf = new UserForum();
            uf.setCreateDate(new Date());
            uf.setForumId(f.getForumId());
            uf.setForumName(f.getTitle());
            uf.setStatus(UserForum.STATUS_NORMAL);
            uf.setUpdateDate(new Date());
            uf.setUserId(userId);
            create(uf);
            count++;
        }
        return count;
    }

    /**
     * 根据用户ID，版块ID，获取关系记录
     *
     * @param userId
     * @param fourmId
     * @return
     */
    public UserForum findByUserIdFourmId(long userId, long forumId) {
        try {
            return geliDao.find(UserForum.class, userId, new Mid(userId, forumId));
        } catch (DataAccessException exception) {
            log.info("Can't find UserForum which userId:{} and forumId:{}.", userId, forumId);
            return null;
        }
    }

    /**
     * 获取用户关注的车友圈
     *
     * @param userId
     * @param status
     * @return
     */
    public List<UserForum> listByUserIdStatus(long userId, int status) {
        SqlBuilder sqlBuilder = new SqlBuilder();
        sqlBuilder.appendSql("select user_id, forum_id from ");
        sqlBuilder.appendSql(geliOrm.getTableName(UserForum.class, userId));
        sqlBuilder.appendSql(" where user_id = ").appendValue(userId);
        sqlBuilder.appendSql(" and status = ").appendValue(status);
        sqlBuilder.appendSql(" order by create_date");

        try {
            List<UserForum> list = geliDao.list(UserForum.class, userId, sqlBuilder.getSql(), sqlBuilder.getValues());
            return list;
        } catch (EmptyResultDataAccessException exception) {
            log.error(" Fail to listByUserIdStatus, sql:{}", sqlBuilder.getSql());
            return Collections.emptyList();
        }
    }

    /**
     * 解绑车友圈
     *
     * @param userId
     * @param forumId
     * @return
     */
    public long deActive(UserForum userForum) {
        try {
            userForum.setStatus(UserForum.STATUS_DELETE);
            return geliDao.update(userForum);
        } catch (DataAccessException exception) {
            log.error("Fail to delete UserForum which userId:{}, forumId:{}.", userForum.getUserId(), userForum.getForumId());
            return 0;
        }
    }

    /**
     * 重绑车友圈
     *
     * @param userId
     * @param forumId
     * @return
     */
    public long active(UserForum userForum) {
        try {
            userForum.setStatus(UserForum.STATUS_NORMAL);
            return geliDao.update(userForum);
        } catch (DataAccessException exception) {
            log.error("Fail to delete UserForum which userId:{}, forumId:{}.", userForum.getUserId(), userForum.getForumId());
            return 0;
        }
    }
}
